#!/usr/bin/python

from google.appengine.api import urlfetch
import logging
import Warehouse
import re

class parser:

    def __init__(self, box):
        self.box=box
        self.dirty=False

    def getMatch(self, match):
        if match is None:
            return None
        #return match.group(1)
        r=""
        for m in match.groups():
            r+=m
        return r

    def readContext(self, url):
        try:
            result = urlfetch.fetch(url)
            if result.status_code == 200:
                return result.content
            else:
                return None
        except urlfetch.InvalidURLError, e:
            logging.error(e)
            return None

    def run(self):
        self.keepref()
        self.dirty=False

        context = self.readContext(self.box.url)

        if context is None:
            return None

        for item,stuff in self.box.stuffs.items():
            b=re.compile(stuff.getPattern())
            match=self.getMatch(b.search(context))
            if match is None:
                logging.error("Bad pattern<%s> of item<%s> at url<%s>",stuff.getpattern(),item,self.box.url)
            else:
                #self.box.setItemValue(item,match)
                stuff.set(match)
                if self.dirty is False:
                    # Wow, It is lambda time! 
                    # [lambda, p1, p2] 
                    lam, p1, p2 = stuff.getExpression()
                    val, ref = stuff.getMatched()
                    fun="lambda val,ref,p1,p2: "+lam
                    self.dirty=eval(fun)(val,ref,p1,p2)
        return self

    def keepref(self):
        self.box.keepref()
                    
    def export(self):
        return self.box.getLabel(), self.box.export()

    def report(self,isHTML=False):
        if self.dirty is True:
            Content=[]
            for item,stuff in self.box.stuffs.items():
                message=stuff.getMessage()
                val, ref=stuff.getMatched()
                if isHTML:
                    Content.append("<p>{}</p>".format(message.format(val,ref)))
                else:
                    Content.append(message.format(val,ref))
            return "\n".join(Content)
        else:
            return None
